import controller from '../controller'
import Wil from '../wil'

cc.Class({
	extends: controller,

	properties: {

	},

	onLoad() {
		controller.prototype.onLoad.call(this)
		this.animation = this.view.body.getComponent(cc.Animation)
		this.player = {
			clothes: 0,
			sex: 0,
			action: 0,
			dir: 4
		}
		this.wil = null
		this.wix = null
		
		let wilurl = cc.assetManager.utils.getUrlWithUuid('cabb2a26-16e2-4d17-8ab4-518599fccaf3', { isNative: true, nativeExt: '.wil' })
		let wixurl = cc.assetManager.utils.getUrlWithUuid('ef5d6b5d-03a1-4bc5-858e-dac3f477050c', { isNative: true, nativeExt: '.WIX' })
		cc.resources.load([{ url: wilurl, ext: '.bin' }, { url: wixurl, ext: '.bin' }], (err, buffers) => {
		//cc.assetManager.loadAny([{ url: 'http://mir2.com/data/Hum.wil', ext: '.bin' }, { url: 'http://mir2.com/data/Hum.wix', ext: '.bin' }], (err, buffers) => {
			this.wil = buffers[0]
			this.wix = buffers[1]
			this.showAnimation()
		})
	},

	mir2Hum() {
		//clothes 1200
		//sex 600
		let start = this.player.clothes * 1200
		start += (this.player.sex) * 600
		start += (this.player.action) * 64
		start += (this.player.dir) * 8
		if(this.player.action > 2){
			start += 8
		}
		if(this.player.action > 7){
			start -= 48
		}
		let numArr = [4,6,6,6,6,8,6,2,3,4] // 站 走 跑 (空8格) 砍 挖矿 跳斩 魔法 挖地(16格) 受击 死亡
		let num = numArr[this.player.action]
		return [start,num]
	},

	loadClip() {
		let wil = new Wil().readWil(this.wil).readWix(this.wix)
		this.spriteFrames = []
		let [start,num] = this.mir2Hum()
		for (let index = 0; index < num; index++) {
			let obj = wil.getImage(index + start, true)
			obj.img.onload = () => {
				let texture = new cc.Texture2D()
				texture.initWithElement(obj.img)
				//texture.handleLoadedTexture()
				let spriteFrame = new cc.SpriteFrame(texture)
				spriteFrame.setOffset(cc.Vec2(obj.offsetX, obj.offsetY))//引擎bug 无法修改偏移
				console.log(spriteFrame)
				this.spriteFrames.push(spriteFrame)
				if(this.spriteFrames.length == num){
					this.addClip(this.player.clothes + '_' + this.player.sex + '_' + this.player.action + '_' + this.player.dir)
				}
			}
		}
		//texture.initWithData(info.buffer, cc.Texture2D.PixelFormat.RGBA8888, info.width, info.height)
	},

	addClip(clipName) {
		let animationClip = cc.AnimationClip.createWithSpriteFrames(this.spriteFrames,4)
		animationClip.speed = 1
		animationClip.wrapMode = cc.WrapMode.Loop
		animationClip.name = clipName
		this.animation.addClip(animationClip)
		this.showAnimation()
	},

	showAnimation() {
		let clipName = null
		this.animation.getClips().forEach(element => {
			if(element.name == this.player.clothes + '_' + this.player.sex + '_' + this.player.action + '_' + this.player.dir){
				clipName = this.player.clothes + '_' + this.player.sex + '_' + this.player.action + '_' + this.player.dir
			}
		})
		if(clipName){
			this.animation.play(clipName)
		}else{
			this.loadClip()
		}
	},

	start() {

	},
	// update (dt) {},
});
